package com.tengfei.main.index.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tengfei.common.core.domain.PageQuery;
import com.tengfei.common.core.page.TableDataInfo;
import com.tengfei.common.utils.StringUtils;
import com.tengfei.main.index.domain.Notice;
import com.tengfei.main.index.domain.bo.NoticeBo;
import com.tengfei.main.index.domain.vo.NoticeVo;
import com.tengfei.main.index.mapper.NoticeMapper;
import com.tengfei.main.index.service.INoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 通知公告Service业务层处理
 *
 * @author tengfei
 * @date 2022-09-03
 */
@RequiredArgsConstructor
@Service
public class NoticeServiceImpl implements INoticeService {

    private final NoticeMapper baseMapper;

    /**
     * 查询通知公告
     */
    @Override
    public NoticeVo queryById(Long noId) {
        return baseMapper.selectVoById(noId);
    }

    /**
     * 查询通知公告列表
     */
    @Override
    public TableDataInfo<NoticeVo> queryPageList(NoticeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Notice> lqw = buildQueryWrapper(bo);
        Page<NoticeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    private LambdaQueryWrapper<Notice> buildQueryWrapper(NoticeBo bo) {
        return new LambdaQueryWrapper<Notice>()
                .eq(ObjectUtil.isNotNull(bo.getNoType()), Notice::getNoType, bo.getNoType())
                .eq(ObjectUtil.isNotNull(bo.getNoIsTop()), Notice::getNoIsTop, bo.getNoIsTop())
                .like(StringUtils.isNotEmpty(bo.getNoTitle()), Notice::getNoTitle, bo.getNoTitle())
                .orderByDesc(Notice::getNoIsTop)
                .orderByDesc(Notice::getUpdateTime);
    }

    /**
     * 新增通知公告
     */
    @Override
    public Boolean insertByBo(NoticeBo bo) {
        Notice add = BeanUtil.toBean(bo, Notice.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setNoId(add.getNoId());
        }
        return flag;
    }

    /**
     * 修改通知公告
     */
    @Override
    public Boolean updateByBo(NoticeBo bo) {
        Notice update = BeanUtil.toBean(bo, Notice.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除通知公告
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
